package com.helloandroid.activitys

import android.graphics.drawable.AnimationDrawable
import android.os.Handler
import android.os.Looper
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.activity.viewModels
import androidx.recyclerview.widget.RecyclerView
import com.business.Analyse
import com.business.AnalyseKey
import com.helloandroid.AppUtil
import com.helloandroid.MyApplication
import com.helloandroid.R
import com.helloandroid.base.BaseActivity
import com.helloandroid.dialogs.AwardDialog
import com.helloandroid.models.butie.SportViewModel
import com.helloandroid.tools.MyLog
import com.helloandroid.tools.MyTimeUtils
import com.helloandroid.tools.NetWorkUtil
import com.helloandroid.vo.MeiRiYunDongInfo
import com.helloandroid.vo.SportDataItem
import com.helloandroid.vo.SportName
import com.helloandroid.vo.SportState
import java.util.*
import kotlin.collections.ArrayList

class SportViewHolder(
        private val rootView: View,
        val ivIcon: ImageView,
        val tvTitle: TextView,
        val tvDesc: TextView,
        val ivCoin: ImageView,
        val tvCoinText: TextView,
        val btn: Button
) : RecyclerView.ViewHolder(rootView)

class SportAdapter(private val mrydActivity: MeiRiYunDongActivity) : RecyclerView.Adapter<SportViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SportViewHolder {
        val rootView = LayoutInflater.from(parent.context).inflate(R.layout.dd_item_daily_sport, parent, false)
        return SportViewHolder(rootView,
                rootView.findViewById(R.id.ivIcon),
                rootView.findViewById(R.id.tvTitle),
                rootView.findViewById(R.id.tvDesc),
                rootView.findViewById(R.id.ivCoin),
                rootView.findViewById(R.id.tvCoinText),
                rootView.findViewById(R.id.btn)
        )
    }

    override fun onBindViewHolder(holder: SportViewHolder, position: Int) {
        val item = MeiRiYunDongActivity.dataLst[position]
        holder.ivIcon.setImageResource(item.iconRes)
        holder.tvTitle.text = item.title
        holder.tvDesc.text = item.desc
        holder.ivCoin.setImageResource(R.drawable.dd_coin_small)
        holder.tvCoinText.text = "+${item.coinCount}"

        when (calSportState(item)) {
            SportState.Getable -> {
                holder.btn.text = "领取"
                holder.btn.setBackgroundResource(R.drawable.btn_red)
                holder.btn.setOnClickListener {
                    mrydActivity.award(item)
                }
            }

            SportState.Geted -> {
                holder.btn.text = "已领取"
                holder.btn.setBackgroundResource(R.drawable.dd_btn_gray)
                holder.btn.setOnClickListener(null)
            }

            SportState.UnCompleted -> {
                holder.btn.text = "进行中"
                holder.btn.setBackgroundResource(R.drawable.btn_blue)
                holder.btn.setOnClickListener(null)
            }

            SportState.UnStarted -> {
                holder.btn.text = "去运动"
                holder.btn.setBackgroundResource(R.drawable.btn_yellow)
                holder.btn.setOnClickListener {
                    MyLog.elog("mrydActivity.gotoPlay......")

                    val str = when (item.key) {
                        SportName.Yuanditiao -> AnalyseKey.Sport_YuandiTiao_Start
                        SportName.Pingpangqiu -> AnalyseKey.Sport_Pingpangqiu_Start
                        SportName.Tizuqiu -> AnalyseKey.Sport_FootBall_Start
                        SportName.Dalanqiu -> AnalyseKey.Sport_Basketball_Start
                        SportName.Paobu -> AnalyseKey.Sport_PaoBu_Start
                        else -> AnalyseKey.Sport_JianShen_Start
                    }
                    Analyse.report(str)

                    mrydActivity.gotoPlay(item)
                }
            }
        }
    }

    override fun getItemCount(): Int {
        return MeiRiYunDongActivity.dataLst.size
    }

    private fun calSportState(dataItem: SportDataItem): SportState {

        val item = mrydActivity.mInfo?.getSportItem(dataItem.key)
        if (item == null) {
            // default
            MyLog.elog("item is null! 还没初始化")
            return SportState.UnStarted
        }

        val sysTime = AppUtil.sysTime
        val sportState: SportState
        if (item.state > 0) {
            // 已领取
            sportState = SportState.Geted
        } else {
            // 1.已开始. 未完成
            // 2. 已开始, 已完成
            // 3.还没有开始
            // 原地跳是1分钟
            sportState = if (item.start > 0) {
                //  已开始
                if (sysTime - item.start >= dataItem.timeMinutes * 60 * 1000) {
                    // 已完成
                    SportState.Getable
                } else {
                    SportState.UnCompleted
                }
            } else {
                // 还没有开始
                SportState.UnStarted
            }
        }
        return sportState
    }
}

class MeiRiYunDongActivity : BaseActivity() {

    companion object {
        val dataLst = ArrayList<SportDataItem>()

        init {
            dataLst.add(SportDataItem(
                    1,
                    SportName.Yuanditiao,
                    R.drawable.dd_mryd_yuanditiao,
                    "原地跳",
                    20,
                    50,
                    1,
                    R.drawable.sport_yuanditiao
            ))

            dataLst.add(SportDataItem(
                    2,
                    SportName.Pingpangqiu,
                    R.drawable.dd_mryd_pingpong,
                    "乒乓球",
                    30,
                    20,
                    3,
                    R.drawable.sport_pingpongqiu
            ))

            dataLst.add(SportDataItem(
                    3,
                    SportName.Tizuqiu,
                    R.drawable.dd_mryd_football,
                    "踢足球",
                    80,
                    280,
                    30,
                    R.drawable.sport_tizuqiu
            ))

            dataLst.add(SportDataItem(
                    4,
                    SportName.Dalanqiu,
                    R.drawable.dd_mryd_basketball,
                    "打篮球",
                    70,
                    160,
                    25,
                    R.drawable.sport_lanqiu
            ))

            dataLst.add(SportDataItem(
                    5,
                    SportName.Paobu,
                    R.drawable.dd_mryd_run,
                    "跑步",
                    60,
                    100,
                    20,
                    R.drawable.sport_paobu
            ))

            dataLst.add(SportDataItem(
                    6,
                    SportName.Jianshencao,
                    R.drawable.dd_mryd_jianshencao,
                    "健身操",
                    50,
                    50,
                    15,
                    R.drawable.sport_jianshencao
            ))
        }
    }

    val model: SportViewModel by viewModels()
    var isReady = false
    var mInfo: MeiRiYunDongInfo? = null

    lateinit var adapter: SportAdapter
    val activityHandler = Handler(Looper.getMainLooper())
    var timer: Timer? = null
    var runItem: SportDataItem? = null

    //-------------

    lateinit var ivAnimView: ImageView
    lateinit var tvTime: TextView
    lateinit var flTimeContainer: FrameLayout

    override fun getContentViewResId() = R.layout.activity_meiriyundong

    override fun initView() {
        ivAnimView = findViewById(R.id.ivAnimView)
//        ivAnimView.scaleY = 0.8f
//        ivAnimView.scaleX = 0.8f

        tvTime = findViewById(R.id.tvTime)
        flTimeContainer = findViewById(R.id.flTimeContainer)
        findBtn(R.id.ibBack).setOnClickListener {
            finish()
        }

        // init listview
        val rvSport = findViewById<RecyclerView>(R.id.rvSport)
        adapter = SportAdapter(this)
        rvSport.adapter = adapter
    }

    override fun initData() {
        //-------------
        model.getInfo { success, info ->
            isReady = success
            if (isReady) {
                mInfo = info
                initUI()
            }
        }
    }

    override fun onDestroy() {
        endTimer()
        super.onDestroy()
    }

    private fun playAnim(animResId: Int) {
        ivAnimView.setImageResource(animResId)

        val iwidth = ivAnimView.drawable.intrinsicWidth
        val iheight = ivAnimView.drawable.intrinsicHeight

        var params = ivAnimView.layoutParams
        if (params == null){
            params = ViewGroup.LayoutParams(0,0)
        }
        params.width = (iwidth * AppUtil.dm.widthPixels / 720f).toInt()
                // resources.getDimension(R.dimen.dp160).toInt()
        params.height = (iheight * AppUtil.dm.widthPixels / 720f).toInt()
                // resources.getDimension(R.dimen.dp320).toInt()
        ivAnimView.layoutParams = params


        (ivAnimView.drawable as AnimationDrawable).start()
    }

    private fun initUI() {
        adapter.notifyDataSetChanged()

        // 1. 判断当前是否有正在进行的?
        runItem = getRunningItem()
        if (null != runItem) {
            // 还要播放相应的动画
            playAnim(runItem!!.gifRes)
            val ms = updateTimeByItem(runItem!!)
            startTimer()

            // 启动一个计时器,进行倒计时
            MyLog.elog("注册一个任务, $ms 毫秒后,执行")
            activityHandler.postDelayed({
                sportEnd()
            }, ms + 1000)
        } else {
            // 播放默认动画
            playAnim(R.drawable.sport_zoulu)
            flTimeContainer.visibility = View.INVISIBLE
        }
    }

    private fun sportEnd() {
        MyLog.elog("运动结束.....")
        endTimer()
        runItem = null
        playAnim(R.drawable.sport_zoulu)
        flTimeContainer.visibility = View.INVISIBLE
        adapter.notifyDataSetChanged()
    }

    private fun getRunningItem(): SportDataItem? {
        if (mInfo == null) {
            return null
        }
        val info = mInfo!!
        val sysTime = AppUtil.sysTime
        return dataLst.find {
            val sportItem = info.getSportItem(it.key)
            val end = sportItem.start + it.timeMinutes * 60 * 1000
            sportItem.state < 1 && sportItem.start > 0 && sysTime >= sportItem.start && sysTime <= end
        }
    }

    fun updateTimeByItem(item: SportDataItem): Long {
        val sportItem = mInfo!!.getSportItem(item.key)
        val endTimeMs = sportItem.start + item.timeMinutes * 60 * 1000
        var ms = endTimeMs - AppUtil.sysTime // 剩余时间
        if (ms >= 0) {
            flTimeContainer.visibility = View.VISIBLE
            tvTime.text = MyTimeUtils.format_mmss(ms)
        } else {
            ms = 0
        }
        return ms
    }

    private fun startTimer() {
        endTimer()
        timer = Timer()
        timer?.schedule(object : TimerTask() {
            override fun run() {
                activityHandler.post {
                    if (runItem == null) {
                        endTimer()
                    } else {
                        updateTimeByItem(runItem!!)
                    }
                }
            }
        }, 1000, 1000)
    }

    fun endTimer() {
        timer?.cancel()
        timer = null
    }


    fun gotoPlay(item: SportDataItem) {
        if (!isReady) {
            return
        }
        MyLog.elog("gotoPlay called!")
        if (runItem != null) {
            AppUtil.toast("请完成正在进行的运动再进行下一次运动!")
            return
        }

        // 在有效的时间内 才能运动
        val sysTime = AppUtil.sysTime
        val ms = MyTimeUtils.getTodayOffsetMs(sysTime)
        if (ms < 5 * 3600 * 1000 || ms > 23 * 3600 * 1000) {
            AppUtil.toast("请在05:00 - 23:00之间进行运动...")
            return
        }

        AppUtil.appViewModel().meiRiYunDongActive(item)
        mInfo?.getSportItem(item.key)?.start = AppUtil.sysTime
        initUI()
    }


    fun award(item: SportDataItem) {
        if (!isReady) {
            return
        }

        if (!NetWorkUtil.networkConnected()) {
            AppUtil.toast("请打开网络!")
            return
        }

        val reason: String
        val str = when (item.key) {
            SportName.Yuanditiao -> {
                reason = AnalyseKey.Sport_YuandiTiao_Video
                AnalyseKey.Sport_YuandiTiao_Award
            }
            SportName.Pingpangqiu -> {
                reason = AnalyseKey.Sport_Pingpangqiu_Video
                AnalyseKey.Sport_Pingpangqiu_Award
            }
            SportName.Tizuqiu -> {
                reason = AnalyseKey.Sport_FootBall_Video
                AnalyseKey.Sport_FootBall_Award
            }
            SportName.Dalanqiu -> {
                reason = AnalyseKey.Sport_Basketball_Video
                AnalyseKey.Sport_Basketball_Award
            }
            SportName.Paobu -> {
                reason = AnalyseKey.Sport_PaoBu_Video
                AnalyseKey.Sport_PaoBu_Award
            }
            else -> {
                reason = AnalyseKey.Sport_JianShen_Video
                AnalyseKey.Sport_JianShen_Award
            }
        }
        Analyse.report(str)

        // 领取奖励
        AppUtil.appViewModel().meiRiYunDongAward(item)
        mInfo?.getSportItem(item.key)?.state = 1

        // 更新数据
        adapter.notifyDataSetChanged()

        // 弹框
        val diaolog = AwardDialog(this, item.coinCount)
        diaolog.reasonKey = reason
        diaolog.show()
    }

    override fun isDarkMode() = false
}